package com.atguigu.gulimall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SkuWareStockTo;
import com.atguigu.common.to.SpuBoundsTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.constant.ProductConstant;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponServiceFeign;
import com.atguigu.gulimall.product.feign.SearchServiceFeign;
import com.atguigu.gulimall.product.feign.WareServiceFeign;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    private int num;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponServiceFeign couponServiceFeign;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private WareServiceFeign wareServiceFeign;
    @Autowired
    private SearchServiceFeign searchServiceFeign;
    @Autowired
    private SpuInfoDao spuInfoDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(w -> w.eq("id", key).or().like("spu_name", key));
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)) {
            wrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotBlank(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catelog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void up(Long spuId) {
        List<ProductAttrValueEntity> attrs = productAttrValueService.listForSpu(spuId);
        //获取产品的所有属性id列表
        List<Long> attrIds = attrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        //过滤出可检索的属性id列表
        List<Long> attrIds2 = attrService.filterAttrIdsBySearchType(attrIds, ProductConstant.SearchType.SEARCHABLE.getCode());
        //过滤出可检索的属性列表
        List<SkuEsModel.Attrs> attrsList = attrs.stream()
                .filter(item -> attrIds2.contains(item.getAttrId()))
                .map(item -> BeanUtil.copyProperties(item, SkuEsModel.Attrs.class))
                .collect(Collectors.toList());
        //查询商品的sku列表
        List<SkuInfoEntity> skuEntities = skuInfoService.findSkuListBySpuId(spuId);
        List<Long> skuIds = skuEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //查库存
        Map<Long, Boolean> stockMap = null;
        try {
            R r = wareServiceFeign.getSkuStock(skuIds);
            TypeReference<List<SkuWareStockTo>> type = new TypeReference<List<SkuWareStockTo>>() {};
            List<SkuWareStockTo> data = r.getData(type);
            Set<SkuWareStockTo> stockSet = new HashSet<>(data);
            stockMap = stockSet.stream().collect(Collectors.toMap(SkuWareStockTo::getSkuId, SkuWareStockTo::getHasStock));
        } catch (Exception e) {
            log.error("远程调用库存服务异常:{}",e);
        }

        //搜集成es数据
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> collect = skuEntities.stream().map(s -> {
            SkuEsModel skuEsModel = BeanUtil.copyProperties(s, SkuEsModel.class);
            skuEsModel.setSkuPrice(s.getPrice());
            skuEsModel.setSkuImg(s.getSkuDefaultImg());
            if (finalStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalStockMap.get(s.getSkuId()));
            }

            skuEsModel.setHotScore(0L);
            BrandEntity brandEntity = brandService.getById(s.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(s.getCatelogId());
            skuEsModel.setCatelogName(categoryEntity.getName());
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());
        //保存到es
        R r = searchServiceFeign.productUp(collect);
        if (r.isSuccess()){
            // 更改为上架状态
            spuInfoDao.updatePublishStatus(spuId,ProductConstant.PublishStatus.ON.getCode());
        }else {
            //todo 多次调用接口幂等性
        }
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息
        SpuInfoEntity spuEntity = BeanUtil.copyProperties(vo, SpuInfoEntity.class);
        spuEntity.setCatelogId(vo.getCatalogId());
        spuEntity.setCreateTime(new Date());
        spuEntity.setUpdateTime(new Date());
        this.save(spuEntity);
        //2、保存spu的描述图片
        List<String> imageDesc = vo.getDecript();
        if (imageDesc != null && imageDesc.size() > 0) {
            SpuInfoDescEntity imageDescEntity = new SpuInfoDescEntity();
            imageDescEntity.setSpuId(spuEntity.getId());
            imageDescEntity.setDecript(String.join(",", imageDesc));
            spuInfoDescService.save(imageDescEntity);
        }
        //3、保存spu的图片集
        spuImagesService.saveSpuImages(spuEntity.getId(), vo.getImages());
        //4、保存spu的规格参数
        productAttrValueService.saveSpuBastAttrs(spuEntity.getId(), vo.getBaseAttrs());
        //5、保存spu的优惠券信息
        if (vo.getBounds() != null) {
            SpuBoundsTo spuBoundsTo = BeanUtil.copyProperties(vo.getBounds(), SpuBoundsTo.class);
            spuBoundsTo.setSpuId(spuEntity.getId());
            R r = couponServiceFeign.saveSpuBounds(spuBoundsTo);
            if (r.getCode() != 0) {
                log.error("远程调用couponServiceFeign服务保存积分失败！");
            }
        }
        //6、保存当前spu对应的所有sku信息
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                String imgUrl = "";
                for (SkuImage img : item.getImages()) {
                    if (img.getDefaultImg() == 1) {
                        imgUrl = img.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = BeanUtil.copyProperties(item, SkuInfoEntity.class);
                skuInfoEntity.setCatelogId(spuEntity.getCatelogId());
                skuInfoEntity.setBrandId(spuEntity.getBrandId());
                skuInfoEntity.setSpuId(spuEntity.getId());
                skuInfoEntity.setSkuDefaultImg(imgUrl);
                skuInfoEntity.setSaleCount(0L);
                //5.1 保存skuInfo信息
                skuInfoService.save(skuInfoEntity);
                if (item.getImages() != null && item.getImages().size() > 0) {
                    List<SkuImagesEntity> collect = item.getImages().stream().map(skuImage -> {
                        SkuImagesEntity skuImagesEntity = BeanUtil.copyProperties(skuImage, SkuImagesEntity.class);
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        return skuImagesEntity;
                    }).filter(image -> StringUtils.isNotBlank(image.getImgUrl())).collect(Collectors.toList());
                    //5.2保存sku图片信息
                    skuImagesService.saveBatch(collect);
                }
                //5.3保存销售属性信息
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = item.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity entity = BeanUtil.copyProperties(attr, SkuSaleAttrValueEntity.class);
                    entity.setSkuId(skuInfoEntity.getSkuId());
                    return entity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);
                //5.4 保存sku满减优惠信息
                SkuReductionTo skuReductionTo = BeanUtil.copyProperties(item, SkuReductionTo.class);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r = couponServiceFeign.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 0) {
                        log.error("远程调用couponServiceFeign服务保存sku满减优惠信息失败！");
                    }
                }
            });
        }
    }

}